
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/services/api.dart';

import 'state.dart';

class CollectCouponsCentreLogic extends GetxController {
  final state = CollectCouponsCentreState();

  @override
  void onInit() {
    super.onInit();
    state.chooseIndex = 0;
  }

  @override
  void onReady() {
    super.onReady();
    var userParams = {
      'access_token': SpUtil.getString('token'), // token
      'mobile': SpUtil.getString('number'),
    };
    Api.searchMember(userParams).listen((event) {
      if (event['code'] == 0) {
        state.userVip = event['vip_type_num_id'].toString();
        String subUnitNumId = SpUtil.getObject(Config.GET_SHOP_INFO)['pickAdrId']?.toString();
        var params = {
          // 'use_platform': 2,
          'sub_unit_num_id': subUnitNumId,
          'vip_type_num_id': event['vip_type_num_id'],  //会员等级
          'access_token': SpUtil.getString('token'), // token
          // 'user_num_id': SpUtil.getInt('empeNumId'), //会员编号
          'page":': state.page,
          'page_size': '1000',
          'item_num_id': 0,
          'tenant_num_id':8,
          'data_sign':0,
        };
        print('params: $params');
        Api.centerCouponsList(params).listen((event) {
          print('++++++> $event');
          state.totalCount = event['count'];
          if (event['card_tickets'] != null) {
            state.couponsCentreList = event['card_tickets'];
          } else {
            state.couponsCentreList = [];
          }
          update();
        });
      }
    });
  }
  /// 下拉刷新
  void refreshData() {
    state.couponsCentreList = [];
    state.page = 1;
    var params = {
      'use_platform': 2,
      'sub_unit_num_id': SpUtil.getInt('storeShopNum'),
      'vip_type_num_id': state.userVip,
      'access_token': SpUtil.getString('token'),
      // 'user_num_id': SpUtil.getInt('empeNumId'), //会员编号
      'page': state.page,
      'page_size': '1000',
    };
    print('下拉刷新  params = $params');
    Api.centerCouponsList(params).listen((event) {
      print('**********************');
      // print(event);
      LogUtil.d(event);
      print('**********************');
      state.totalCount = event['count'];
      if (event['card_tickets'] != null) {
        state.couponsCentreList = event['card_tickets'];
      } else {
        state.couponsCentreList = [];
      }
      state.controller1.refreshCompleted();
      update();
    });
  }
  // /// 上拉加载更多
  // void loadMoreData() {
  //   state.page = state.page + 1;
  //   var params = {
  //     'use_platform': 2,
  //     'sub_unit_num_id': 102002,
  //     'vip_type_num_id': state.userVip,
  //     'access_token': SpUtil.getString('token'),
  //     'user_num_id': SpUtil.getInt('empeNumId'), //会员编号
  //     'page_no":': state.page,
  //     'page_size': '1000',
  //   };
  //   print('上拉加载更多  params = $params');
  //   Api.centerCouponsList(params).listen((event) {
  //     state.totalCount = event['count'];
  //     List list = state.couponsCentreList;
  //     if (event['card_tickets'] != null) {
  //       list.addAll(event['card_tickets']);
  //       state.couponsCentreList = list;
  //       state.controller1.loadComplete();
  //     } else {
  //       state.controller1.loadComplete();
  //     }
  //     update();
  //   });
  // }
  // 领取优惠券
  void getCoupon({
    String coupon_num_id,
    int index,
    BuildContext context
  }) {
    var params ={
      "use_platform": 2,
      "coupon_num_id": coupon_num_id,//券编码
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "access_token": SpUtil.getString('token'),
      "relation": "领券中心",
      "qsource": 301,
      "relation_indate": "永久有效",
      "user_num_id": SpUtil.getInt('empeNumId'),
    };
    Api.getCoupon(params).listen((event) {
      print('领取优惠券  数据 $event');
      FToast fToast = FToast();
      fToast.init(context);

      if (event['code'] == 0) {
        Map<String, dynamic> dataMap = state.couponsCentreList[index];
        // '限领${dataMap['limit_usr_number']}张 已领${dataMap['is_receive_count']}张',
        dataMap['is_receive_count'] = dataMap['is_receive_count'] + 1;
        fToast.showToast(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: setWidth(200),
                height: setWidth(200),
                decoration: BoxDecoration(
                  color: Color(0xff333333),
                  borderRadius: BorderRadius.circular(setWidth(20)),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.done_rounded,
                      color: Colors.white,
                      size: 40,
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    Text(
                      '领取成功',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 15,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          gravity: ToastGravity.CENTER,
          toastDuration: Duration(seconds: 2),
        );
      } else {
        // fToast.showToast(
        //   child: Column(
        //     mainAxisAlignment: MainAxisAlignment.center,
        //     children: [
        //       Container(
        //         width: setWidth(200),
        //         height: setWidth(200),
        //         decoration: BoxDecoration(
        //           color: Color(0xff333333),
        //           borderRadius: BorderRadius.circular(setWidth(20)),
        //         ),
        //         child: Column(
        //           mainAxisAlignment: MainAxisAlignment.center,
        //           children: [
        //             Icon(
        //               Icons.clear,
        //               color: Colors.white,
        //               size: 40,
        //             ),
        //             SizedBox(
        //               width: 5,
        //             ),
        //             Text(
        //               '领取失败',
        //               style: TextStyle(
        //                 color: Colors.white,
        //                 fontSize: 15,
        //               ),
        //             ),
        //           ],
        //         ),
        //       ),
        //     ],
        //   ),
        //   gravity: ToastGravity.CENTER,
        //   toastDuration: Duration(seconds: 2),
        // );
      }
      update();
    });
  }

  String faceValue(String faceValue){
    double faceValueDoub = double.parse(faceValue);
    double dou = faceValueDoub / 10;
    return dou.toStringAsFixed(2);
  }


  void onChooseChange(int index) {
    state.chooseIndex = index;
    onReady();
    update();
  }

  @override
  void dispose() {
    super.dispose();
    state.controller1.dispose();
    update();
  }
}